package com.jz.main.io.file;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

public class FileReadWriteExample {

    public static void main(String[] args) {
        String filePath = "example.txt"; // 文件路径
        String dataToWrite = "Hello, World!"; // 要写入的数据

        // 写入文件
        writeFile(filePath, dataToWrite);

        // 读取文件
        String dataRead = readFile(filePath);
        System.out.println("Data read from file: " + dataRead);
    }

    // 写入文件
    private static void writeFile(String filePath, String data) {
        try (RandomAccessFile file = new RandomAccessFile(filePath, "rw");
             FileChannel channel = file.getChannel()) {

            byte[] byteData = data.getBytes();
            ByteBuffer buffer = ByteBuffer.allocate(byteData.length);
            buffer.put(byteData);
            buffer.flip();

//            ByteBuffer.allocateDirect();
            FileOutputStream os = new FileOutputStream("");
            os.flush();
            os.close();
            // 将数据写入文件
            channel.write(buffer);

            System.out.println("Data has been written to file.");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    // 读取文件
    private static String readFile(String filePath) {
        StringBuilder content = new StringBuilder();
        try (RandomAccessFile file = new RandomAccessFile(filePath, "r");
             FileChannel channel = file.getChannel()) {

            ByteBuffer buffer = ByteBuffer.allocate(1024);

            // 从文件通道读取数据到缓冲区
            while (channel.read(buffer) != -1) {
                buffer.flip(); // 切换至读模式
                while (buffer.hasRemaining()) {
                    content.append((char) buffer.get()); // 从缓冲区读取数据并追加到内容中
                }
                buffer.clear(); // 清空缓冲区，准备下一次读取
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return content.toString();
    }
}

